<!DOCTYPE html>
<html lang="zh-cn">
	<head>
		<meta charset="UTF-8" />
		<meta name="viewport" content="width=device-width, initial-scale=1.0" />
		<meta http-equiv="X-UA-Compatible" content="ie=edge" />
		<title>虚拟滚动</title>
		<link rel="shortcut icon" href="https://dummyimage.com/24x24/4A7BF7&text=%E8%99%9A" type="image/x-icon" />
		<link rel="stylesheet" href="./style.css" />
	</head>
	<body>
		<ul id="main"></ul>
		<div id="btns" title="请查看控制台">
			<div class="btn" onclick="viewDom()">查看渲染</div>
			<div class="btn" onclick="viewDataSource()">查看数据源</div>
			<div class="btn" onclick="reloadData()">重置内容</div>
		</div>
		<!-- 生产环境应使用lib下的js，开发环境可使用src下的js -->
		<script src="./src/index.js"></script>
		<script src="https://cdn.bootcss.com/Mock.js/1.0.0/mock-min.js"></script>
		<script>
			var total = 0;
			var Random = Mock.Random;
			var jhVScroller = new JhVirtualScroll(document.querySelector('#main'), {
				fetch: function() {
					return new Promise(function(resolve, reject) {
						var items = [];
						if (total < 100 * 10) {
							for (var i = 0; i < 30; i++) {
								items.push({
									id: ++total,
									avatar: Random.dataImage('48x48', Random.cfirst()),
									time: new Date(
										Math.floor(new Date().getTime() + i * 20 * 1000 + Math.random() * 20 * 1000)
									),
									message: Random.ctitle(20, 50),
								});
							}
						}
						resolve(items);
					});
				},
				skeleton: function() {
					var h1 = document.createElement('h1');
					h1.textContent = '我是骨架元素';
					return h1;
				},
				render: function(data) {
					var li = document.createElement('li');
					li.classList.add('chat-item');
					li.innerHTML = `
						<img class="avatar" width="48" height="48" src='${data.avatar}' />
						<div class="bubble">
							<p><strong>${data.id}</strong>  ${data.message}</p>
							<div class="meta"><time class="posted-date">${data.time.toString()}</time></div>
						</div>
					`;
					return li;
				},
			});

			function consoleTitle(title) {
				console.log(
					'%c 虚拟滚动 %c ' + title + ' %c',
					'background:#35495e ; padding: 1px; border-radius: 3px 0 0 3px;  color: #fff',
					'background:#41b883 ; padding: 1px; border-radius: 0 3px 3px 0;  color: #fff',
					'background:transparent;'
				);
			}

			function viewDom() {
				var arr = {};
				consoleTitle('查看渲染');
				arr['子节点数'] = jhVScroller.el.childElementCount;
				arr['后代节点数'] = forEachChild(jhVScroller.el.childNodes);
				console.table(arr);
			}

			function forEachChild(list) {
				var sum = 0;
				for (var i = 0; i < list.length; i++) {
					sum++;
					if (list[i].childElementCount) {
						sum += forEachChild(list[i].childNodes);
					}
				}
				return sum;
			}

			function viewDataSource() {
				consoleTitle('查看数据源');
				console.table(jhVScroller.vnodeList);
			}

			function reloadData() {
				consoleTitle('重置内容');
				jhVScroller.onReload(function() {
					total = 0;
				});
			}
		</script>
	</body>
</html>
